﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using com.paypal.soap.api;
using System.Data;
using System.Web.Security;
using ASPDotNetSamples;
using System.Net;
using System.Net.Mail;


public partial class Front_ECReceipt : BasePage
{
    ASPDotNetSamples.BasePage basepage = new ASPDotNetSamples.BasePage();
    private void Page_Load(object sender, EventArgs e)
    {
        //setSecureProtocol(true);
        if (!IsPostBack)
        {
            BindReferData();
            BindDealData();
            //divSubcrigePopUp.Show();
            PayPalAPI api = new PayPalAPI();
            this.PayPalResponse = api.DoExpressCheckoutPayment(this.Token, this.PayerID, this.PaymentAmount, this.PaymentAction, Currency);
            this.DataBind();

            Response.Redirect("~/MyAccountSettings.aspx?Popup=1&tab=0");
        }

    }
    public void BindDealData()
    {
        Session["username"] = Membership.GetUser().UserName.ToString();
        if (Session["username"] != null)
        {
            selectProduct();
            FillCrdeitAmount();
        }
    }
    public void selectProduct()
    {
        txtQuantity.Enabled = false;
        txtQuantity.Text = Session["Quantity"].ToString();
        var a = new DealesDataContext();
        var query = a.SelectProduct_Deal(Convert.ToInt32(Session["DealID"]));
        foreach (var item in query)
        {
            lblDescription.Text = item.ShortDescription;
            lblPrice.Text = (System.Math.Round(double.Parse(item.SellPrice.ToString()), 2)).ToString();
            lblTotalPrice.Text = (Convert.ToDouble(lblPrice.Text) * Convert.ToDouble(txtQuantity.Text)).ToString();
            lblYourTotal.Text = (Convert.ToDouble(lblPrice.Text) * Convert.ToDouble(txtQuantity.Text)).ToString();
            Session["TotalPrice"] = lblTotalPrice.Text;
            Session["Price"] = lblPrice.Text;
            Session["Quantity"] = txtQuantity.Text;
            ExpireDate.Text = " Expire: " + Convert.ToDateTime(item.ExpirationDate.ToString()).ToShortDateString();
            DealImg.ImageUrl = "Admin/ImageDisplay.aspx?DealID=" + item.DealID;

        }
        lblCredit.Text = "(0)";
        lblCredit.Visible = false;
        Credit.Visible = false;
        var query2 = new DealesDataContext();
        var CheckQtyQuery = query2.Select_MaxQtyFromDeal(Convert.ToInt32(Session["DealID"].ToString()));
        int LimitPerPerson = 0;
        foreach (var j in CheckQtyQuery)
        {
            LimitPerPerson = Convert.ToInt32(j.limitperperson);
        }
        if (LimitPerPerson == 1)
        {
            txtQuantity.Enabled = false;
        }
    }
    public void FillCrdeitAmount()
    {
        try
        {
            var credit = new DealesDataContext();
            var Amount = credit.GetCreditAmount(new Guid(Membership.GetUser().ProviderUserKey.ToString()));
            double money = 0.0;
            double referMoney = 0.0;
            ViewState["RferAmount"] = money;
            lblCredit.Text = "(0)";
            lblCredit.Visible = false;
            Credit.Visible = false;
            foreach (var item in Amount)
            {
                if (item.amount.ToString() != "0")
                {
                    money = Convert.ToDouble(item.amount.ToString());
                    if (money > 0)
                    {
                        //  lblFinalPrice.Visible = true;
                        // lblFinalPrice.Text = "<b>Congratulations!</b> You have $" + money + " Zupons credit that will be applied to this purchase.";
                        lblCredit.Text = "(" + money + ")";
                        lblCredit.Visible = true;
                        Credit.Visible = true;
                    }
                    ViewState["RferAmount"] = money;
                    var referAmount = credit.GetReferAmount(new Guid(Membership.GetUser().ProviderUserKey.ToString()));
                    foreach (var items in referAmount)
                    {
                        if (items.ReferAmount != null)
                        {
                            referMoney = Convert.ToDouble(items.ReferAmount.ToString());
                            if ((money - referMoney) == 0.0)
                            {

                                lblFinalPrice.Visible = false;
                                lblCredit.Visible = false;
                                Credit.Visible = false;
                            }
                            else
                            {
                                //  lblFinalPrice.Visible = true;
                                //  lblFinalPrice.Text = "<b>Congratulations!</b> You have $" + (money - referMoney) + " Zupons credit that will be applied to this purchase.";
                                lblCredit.Text = "(" + (money - referMoney) + ")";
                                lblCredit.Visible = true;
                                Credit.Visible = true;
                            }
                            ViewState["RferAmount"] = (money - referMoney);
                        }
                    }
                }
            }

            double RferAmount = Convert.ToDouble(ViewState["RferAmount"].ToString());
            double TotalPrice = Convert.ToDouble(Session["TotalPrice"].ToString());
            if (TotalPrice > RferAmount)
            {
                Session["ReferAmount"] = Convert.ToDouble(ViewState["RferAmount"].ToString());
                Session["TotalPrice"] = Convert.ToDouble(Session["TotalPrice"].ToString()) - Convert.ToDouble(ViewState["RferAmount"].ToString());
                lblYourTotal.Text = Session["TotalPrice"].ToString();
                ViewState["CreditZero"] = null;
            }
            else
            {
                // Session["ReferAmount"] = Convert.ToDouble(ViewState["RferAmount"].ToString()) - Convert.ToDouble(Session["TotalPrice"].ToString());
                Session["ReferAmount"] = lblPrice.Text;
                lblYourTotal.Text = "0";
                Session["TotalPrice"] = "0";
                ViewState["CreditZero"] = 1;
            }

        }
        catch
        {
        }
    }
    public string GetDealID()
    {
        string CityID;
        string DealID = "0";
        if (Request.Cookies["CityID"] != null)
        {
            CityID = Request.Cookies["CityID"].Value;
            var sub = new DealesDataContext();
            var getDealID = sub.Select_DealByCityIDNew(Convert.ToInt32(CityID));
            foreach (var item in getDealID)
            {
                DealID = item.DealID.ToString();

            }
        }
        return DealID;
    }
    public void BindReferData()
    {
        string CityID = "";
        if (Request.Cookies["CityID"] != null)
        {
            CityID = Request.Cookies["CityID"].Value;
        }
        string UserID = Membership.GetUser().ProviderUserKey.ToString();
        var sub = new DealesDataContext();
        var query1 = sub.Select_DealByCityIDNew(Convert.ToInt32(CityID));
        int DealID = 0;
        foreach (var item in query1)
        {
            DealID = Convert.ToInt32(item.DealID);
        }
        textLink.Text = "http://www.zupons.com/Default.aspx?ReferUserID=" + UserID + "&CityID=" + CityID.ToString();
        Twiteer.HRef = "http://twitter.com/home?status=https://www.zupons.com/Default.aspx?dealID=" + DealID.ToString();

        FaceBook.HRef = "http://www.facebook.com/sharer.php?u=https://www.zupons.com/Default.aspx?dealID=" + DealID.ToString();


    }
    protected void btnReferSend_Click(object sender, EventArgs e)
    {
        try
        {

            string Url = "<a href=" + textLink.Text + ">" + textLink.Text + "</a>";
            //System.Collections.Specialized.ListDictionary replacements = new System.Collections.Specialized.ListDictionary();
            //replacements.Add("<%From%>", txtFrom.Text);
            //replacements.Add("<%MailSubject%>", Url);
            //System.Net.Mail.MailMessage confirmation = Mailer.CreateMessage(new System.Web.UI.Control() as WebControl, Mailer.MessageTemplate.ReferLink, replacements, txtTo.Text.ToString(), "Refer Friends");
            //Mailer.InternalSend(confirmation, false);
            MailMessage Mail = new MailMessage();
            MailAddress ma = new MailAddress("mail@zupons.com", "Zupons");
            Mail.From = ma;
            Mail.To.Add(txtTo.Text.ToString());
            Mail.Subject = "Refer Friends";
            Mail.Body = Url;
            Mail.IsBodyHtml = true;
            try
            {
                SmtpClient smtpMailObj = new SmtpClient();
                smtpMailObj.Host = "mail.zupons.com";
                smtpMailObj.Send(Mail);
                // Response.Write("Your Message has been sent successfully");
            }
            catch (Exception ex)
            {
                //Response.Write("Message Delivery Fails");
            }
            txtErrorMsg.Visible = true;
            txtErrorMsg.Text = "Message Sent successfully.";
            txtTo.Text = "";
            txtFrom.Text = "";
            divSubcrigePopUp.Show();
        }
        catch (Exception ex)
        {
            txtErrorMsg.Visible = true;
            txtErrorMsg.Text = ex.Message;
        }
    }
    protected void BtnCancel_Click(object sender, EventArgs e)
    {
        To.Visible = false;
        From.Visible = false;
        Send.Visible = false;
        txtTo.Text = "";
        txtFrom.Text = "";
        txtErrorMsg.Text = "";
        divSubcrigePopUp.Show();
    }
    protected void lnkBtnMailIt_Click(object sender, EventArgs e)
    {
        To.Visible = true;
        From.Visible = true;
        Send.Visible = true;
        txtTo.Text = "";
        txtFrom.Text = "";
        txtErrorMsg.Text = "";
        divSubcrigePopUp.Show();
    }
    protected void Image3_Click(object sender, ImageClickEventArgs e)
    {
        divSubcrigePopUp.Show();
        To.Visible = true;
        From.Visible = true;
        Send.Visible = true;
        txtTo.Text = "";
        txtFrom.Text = "";
        txtErrorMsg.Text = "";
    }
    protected void DealImg_Click(object sender, ImageClickEventArgs e)
    {

    }
    public void setSecureProtocol(bool bSecure)
    {
        string redirectUrl = null;

        // if we want HTTPS and it is currently HTTP
        if (bSecure && !Request.IsSecureConnection)
            redirectUrl = Request.Url.ToString().Replace("http:", "https:");

        else

            // if we want HTTP and it is currently HTTPS
            if (!bSecure && Request.IsSecureConnection) redirectUrl = Request.Url.ToString().Replace("https:", "http:");

        //else

        // in all other cases we don't need to redirect

        // check if we need to redirect, and if so use redirectUrl to do the job
        if (redirectUrl != null)

            Response.Redirect(redirectUrl);

    }
    static IEnumerable<string> GetRandomNumbers(int noOfRandomNumbers)
    {
        string allowedChars = "0123456789";
        Random rd = new Random();
        var mySet = new HashSet<string>();
        char[] chars = new char[6];
        for (int i = 0; i < noOfRandomNumbers; i++)
        {

            string s = "";
            for (int j = 0; j < 10; j++)
            {
                s += allowedChars[rd.Next(0, allowedChars.Length)];
            }
            while (!mySet.Add(s))
            {

                for (int j = 0; j < 10; j++)
                {
                    s += allowedChars[rd.Next(0, allowedChars.Length)];
                }
            }

            yield return s;
        }
    }
    public override void DataBind()
    {
        try
        {
            this.SuccessfulPlaceholder.Visible = this.IsTransactionSuccessful;
            var paymentDetails = new DealesDataContext();
            if (this.Receipt != null && this.IsTransactionSuccessful)
            {
                //divSubcrigePopUp.Show();
                this.SuccessfulPlaceholder.DataBind();

                string ID = "";
                string orderID = "";
                string UserID = Membership.GetUser().ProviderUserKey.ToString();

                DataTable dttemp = (DataTable)Session["dtTemp"];
                DataTable dtGift = (DataTable)Session["dtGift"];
                if (dttemp != null)
                {
                    if (Session["ReferAmount"] != null)
                    {
                        if (Convert.ToDouble(Session["ReferAmount"]) > 0.0)
                        {
                            var query = paymentDetails.ReferUserAmount_Insert(new Guid(Convert.ToString(UserID)), Convert.ToDecimal(Session["ReferAmount"]));
                        }
                    }
                    var QueryReferUser = paymentDetails.Select_ReferUser(new Guid(Convert.ToString(UserID)));
                    foreach (var item in QueryReferUser)
                    {
                        var QueryUpdateReferUser = paymentDetails.Update_ReferUser(new Guid(Convert.ToString(UserID)));
                    }
                    if (dtGift != null)
                    {
                        var query = paymentDetails.Insert_UserPaymentDetails(dttemp.Rows[0]["Address1"].ToString(), dttemp.Rows[0]["Address1"].ToString(), Convert.ToString(this.Receipt.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID), Convert.ToDouble(this.Receipt.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].GrossAmount.Value), "", "", dttemp.Rows[0]["city"].ToString(), dttemp.Rows[0]["state"].ToString(), dttemp.Rows[0]["zip"].ToString(), Convert.ToInt32(Session["Quantity"]), Convert.ToDecimal(Session["Price"]), Convert.ToDecimal(Session["TotalPrice"]), Convert.ToInt32(Session["DealID"]), new Guid(Convert.ToString(UserID)), ID, dtGift.Rows[0]["To"].ToString(), dtGift.Rows[0]["From"].ToString(), dtGift.Rows[0]["Message"].ToString(), dtGift.Rows[0]["EmailTo"].ToString(), Convert.ToInt32(dtGift.Rows[0]["Delivery"]), 1, dttemp.Rows[0]["CCNo"].ToString());
                        foreach (var item in query)
                        {
                            orderID = item.orderID.ToString();
                        }
                        foreach (var number in GetRandomNumbers(Convert.ToInt32(Session["Quantity"])))
                        {
                            var insertCoupons = paymentDetails.Insert_CouponsCode(Convert.ToInt32(orderID), number);
                            LitCouponID.Text += number + ",";
                        }
                    }
                    else
                    {
                        var query = paymentDetails.Insert_UserPaymentDetails(dttemp.Rows[0]["Address1"].ToString(), dttemp.Rows[0]["Address1"].ToString(), Convert.ToString(this.Receipt.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID), Convert.ToDouble(this.Receipt.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].GrossAmount.Value), "", "", dttemp.Rows[0]["city"].ToString(), dttemp.Rows[0]["state"].ToString(), dttemp.Rows[0]["zip"].ToString(), Convert.ToInt32(Session["Quantity"]), Convert.ToDecimal(Session["Price"]), Convert.ToDecimal(Session["TotalPrice"]), Convert.ToInt32(Session["DealID"]), new Guid(Convert.ToString(UserID)), ID, "", "", "", "", 0, 0, dttemp.Rows[0]["CCNo"].ToString());
                        foreach (var item in query)
                        {
                            orderID = item.orderID.ToString();
                        }
                        foreach (var number in GetRandomNumbers(Convert.ToInt32(Session["Quantity"])))
                        {
                            var insertCoupons = paymentDetails.Insert_CouponsCode(Convert.ToInt32(orderID), number);
                            LitCouponID.Text += number + ",";
                        }
                    }

                    LitCouponID.Text = LitCouponID.Text.Remove(LitCouponID.Text.Length - 1, 1);

                }

                var Email = paymentDetails.Select_aspnet_Membership(Convert.ToString(UserID));

                var Desp = new DealesDataContext();
                var DealDesp = Desp.SelectProduct_Deal(Convert.ToInt32(Session["DealID"].ToString()));
                string DealDescription = "";
                foreach (var item in DealDesp)
                {

                    DealDescription = item.Name;

                }

                foreach (var item in Email)
                {


                    string EmailText = "<table width=\"70%\" style=\"border-color:#008800; border-width: 15px; border-style: solid;\"><tr><td align=\"center\"><br /><img src=\"http://www.zupons.com/Images/logo.png\"/></td></tr><tr><td><b>Hello " + item.FirstName.ToString() + ",</b><br />Your Zupons voucher is ready to print by signing in to your account at  <a href=\"http://www.zupons.com/Login.aspx\" runat=\"server\">http://www.zupons.com/MyZupons</a>  . Here is your order details:<br /><br /></td></tr><tr><td><br /><b>Your Order Details:</b></td></tr><tr><td align=\"left\"><b>Deal:</b>" + DealDescription + "</td></tr><tr><td align=\"left\"><b>Order Quantity:</b>" + Session["Quantity"].ToString() + "</td></tr><tr><td></td></tr><tr><td align=\"left\"><b>Total charged to your credit :</b>$" + Session["TotalPrice"].ToString() + "</td></tr><tr><td><br /><br />Thanks for your order !</td></tr><tr><td> <br /> The Zupons Team<br /><a href=\"http://www.zupons.com\" runat=\"server\">http://www.zupons.com</a></td></tr><tr><td><br />P.S. Remember to check daily for your next Zupons deal.<br /><br /></td></tr><tr style=\"border-color: #80FE80; border-width: 15px; border-style: solid; background: #ddedcc;\"align=\"center\"> <td> <br />Need Help ? Have FeedBack ? Feel Free To <a href=\"http://www.zupons.com/ContactUs.aspx\" runat=\"server\">ContactUs</a><br /> <br /></td></tr></table>";
                    MailMessage Mail = new MailMessage();
                    MailAddress ma = new MailAddress("mail@zupons.com", "Zupons");
                    Mail.From = ma;
                    Mail.To.Add(item.Email.ToString());
                    Mail.Subject = "Thanks for your Zupons order !";
                    Mail.Body = EmailText;
                    Mail.IsBodyHtml = true;
                    try
                    {
                        SmtpClient smtpMailObj = new SmtpClient();
                        smtpMailObj.Host = "mail.zupons.com";
                        smtpMailObj.Send(Mail);
                        //  Response.Write("Your Message has been sent successfully");
                    }
                    catch (Exception ex)
                    {
                        //Response.Write("Message Delivery Fails");
                    }
                    //System.Collections.Specialized.ListDictionary replacements = new System.Collections.Specialized.ListDictionary();                 
                    //replacements.Add("<%UserName%>", EmailText);
                    //System.Net.Mail.MailMessage confirmation = Mailer.CreateMessage(new System.Web.UI.Control() as WebControl, Mailer.MessageTemplate.NewOrder, replacements, item.Email.ToString(), "Thanks for your Zupons order !");
                    //Mailer.InternalSend(confirmation, false);
                }
            }
            else
            {
                PayPalError.Visible = true;

            }
        }
        catch (Exception x)
        {
        }
    }

    protected CurrencyCodeType Currency
    {
        get
        {
            return (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), this.Request.QueryString.Get(Constants.PAYMENT_CURRENCY_PARAM));
        }
    }

    protected string Token
    {
        get
        {
            return this.Request.QueryString.Get(Constants.TOKEN_PARAM);
        }
    }

    protected string PayerID
    {
        get
        {
            return this.Request.QueryString.Get(Constants.PAYERID_PARAM);
        }
    }

    protected string PaymentAmount
    {
        get
        {
            return this.Request.QueryString.Get(Constants.PAYMENT_AMOUNT_PARAM);
        }
    }

    protected DoExpressCheckoutPaymentResponseType Receipt
    {
        get
        {
            return (DoExpressCheckoutPaymentResponseType)this.PayPalResponse;
        }
    }

    protected void imgClose_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("~/MyAccountSettings.aspx");
    }
}
